package com.showtao.front.service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.cxf.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.showtao.common.enumeration.EErrorCode;
import com.showtao.common.exception.BizServiceException;
import com.showtao.common.security.repository.UserRepository;
import com.showtao.front.domain.MobileOrder;
import com.showtao.front.domain.Order;
import com.showtao.front.domain.OrderValidationCode;
import com.showtao.front.repository.MobileOrderRepository;
import com.showtao.front.repository.OrderRepository;
import com.showtao.front.repository.OrderValidationCodeRepository;

@Service
public class OrderService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private OrderValidationCodeRepository orderValidationCodeRepository;
    @Autowired
    private SMSService smsService;
    @Autowired
    MobileOrderRepository mobileOrderRepository;
    
    @Transactional(readOnly = true)
    public Page<Order> findOrdersByMobile(String mobile, Pageable pageable){
        return orderRepository.findByReceiverPhone(mobile, pageable);
    }
    
    @Transactional
    public void sendValidationCode(String mobile){
        if (StringUtils.isEmpty(mobile)) {
            throw new BizServiceException(EErrorCode.COMM_INTERNAL_ERROR,
                    "参数不正确");
        }
        OrderValidationCode ovc = orderValidationCodeRepository.getByMobile(mobile);
        if(ovc == null){
            ovc = new OrderValidationCode();
            ovc.setCreatedAt(Calendar.getInstance().getTime());
            ovc.setMobile(mobile);
        }
        DecimalFormat df = new DecimalFormat("0000");
        String code = df.format(Math.round(Math.random()*1000));
        smsService.sendMessage(mobile, "秀套网订单查询验证码：【"+code+"】，半小时内有效，打死都不告诉别人哦！");
        ovc.setCode(code);
        ovc.setUpdatedAt(Calendar.getInstance().getTime());
        orderValidationCodeRepository.save(ovc);
    }
    
    @Transactional
    public void validateCode(String mobile, String code){
        if (StringUtils.isEmpty(code)) {
            throw new BizServiceException(EErrorCode.COMM_INTERNAL_ERROR,
                    "参数不正确");
        }
        OrderValidationCode ovc = orderValidationCodeRepository.getByMobile(mobile);
        if(ovc==null){
            throw new BizServiceException(EErrorCode.COMM_INTERNAL_ERROR, "验证码"+code+"无效");
        }else if(StringUtils.isEmpty(ovc.getCode()) || ovc.getUpdatedAt() == null){
            throw new BizServiceException(EErrorCode.COMM_INTERNAL_ERROR, "验证码"+code+"已失效");
        }else if(!code.equals(ovc.getCode())){
            throw new BizServiceException(EErrorCode.COMM_INTERNAL_ERROR, "验证码"+code+"不正确");
        }else {
            Calendar c = Calendar.getInstance();
            c.setTime(ovc.getUpdatedAt());
            c.add(Calendar.MINUTE, 30);
            if(c.before(Calendar.getInstance())){
                throw new BizServiceException(EErrorCode.COMM_INTERNAL_ERROR, "验证码"+code+"已过期");
            }
        }
        ovc.setCode(null);
        ovc.setUpdatedAt(Calendar.getInstance().getTime());
        orderValidationCodeRepository.save(ovc);
    }
    
    public List<Order> findByReceiverPhoneAndOrderDate(String receiverPhone, Date startDate, Date endDate) throws Exception{
    	if(startDate==null){
    		Calendar c = Calendar.getInstance();
    		c.set(Calendar.YEAR, 1970);
    		c.set(Calendar.MONTH, 0);
    		c.set(Calendar.DAY_OF_MONTH, 1);
    		c.set(Calendar.HOUR_OF_DAY, 0);
    		c.set(Calendar.MINUTE, 0);
    		c.set(Calendar.SECOND, 0);
    		c.set(Calendar.MILLISECOND, 0);
    		startDate=c.getTime();
    	}
    	if(endDate==null){
    		endDate=new Date();
    	}
    	
    	return orderRepository.findByReceiverPhoneAndOrderDate(receiverPhone, startDate, endDate);
    }
    
    public List<MobileOrder> findMobileOrderByMobileAndCreatedDate(String mobile, Date startDate, Date endDate) throws Exception{
    	if(startDate==null){
    		Calendar c = Calendar.getInstance();
    		c.set(Calendar.YEAR, 1970);
    		c.set(Calendar.MONTH, 0);
    		c.set(Calendar.DAY_OF_MONTH, 1);
    		c.set(Calendar.HOUR_OF_DAY, 0);
    		c.set(Calendar.MINUTE, 0);
    		c.set(Calendar.SECOND, 0);
    		c.set(Calendar.MILLISECOND, 0);
    		startDate=c.getTime();
    	}
    	if(endDate==null){
    		endDate=new Date();
    	}
    	
    	return mobileOrderRepository.findMobileOrderByMobileAndCreatedDate(mobile, startDate, endDate);
    }
    
    @Transactional
    public void saveMobileOrder(MobileOrder order){
    	if(order.getOrderNo()==null || order.getOrderNo().length()==0){
    		order.setOrderNo(System.currentTimeMillis()+"");
    	}
    	mobileOrderRepository.save(order);
    }
}
